package controllers

import (
	"encoding/json"
	"errors"
	"strconv"
	"time"

	"cashew.com/cashew_api/dtos"
	"cashew.com/cashew_api/models"
	"cashew.com/cashew_api/services"
	"cashew.com/cashew_common/configs"
	"cashew.com/cashew_common/constants"
	"cashew.com/cashew_common/utils"
	"github.com/beego/beego/v2/client/orm"
)

type AnchorController struct {
	BaseController
}

// 获取主播资料
func (c *AnchorController) GetAnchorInfo() {

	req := dtos.AnchorGetAnchorInfoParams{}

	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误: ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	// 获取主播信息
	var anchorInfo *models.Anchor_info
	anchorInfo, err = models.GetAnchor_infoByAnchorId(req.UserId)
	if err != nil {
		c.Info("查询anchor_info失败:", err.Error())
		c.Result(constants.ERR_USER_DATA_EXCPTION, nil)
		return
	}

	// 获取视频通话价格信息
	priceList, err := models.GetVideo_call_pricesByAnchorAndType(anchorInfo.AnchorId, constants.PRICE_TYPE_ID_VIDEO_CALL)
	if err != nil {
		c.Info("查询video_call_price失败:", err.Error())
		c.Result(constants.ERR_USER_DATA_EXCPTION, nil)
		return
	}

	// 构建价格数据
	priceData := []dtos.PriceData{}
	priceConfig := &models.Video_call_price_config{}
	for _, v := range priceList {
		priceConfig, err = models.GetVideo_call_price_configById(v.Price)

		if err != nil {
			c.Error("查询video_call_price_config失败:", err.Error())
			continue
		}

		if v.PriceType == constants.PRICE_TYPE_ID_VIDEO_CALL {
			priceData = append(priceData, dtos.PriceData{PriceType: constants.PRICE_TYPE_CODE_VIDEO_CALL, PayPrice: int(priceConfig.PayPrice)})
		} else if v.PriceType == constants.PRICE_TYPE_ID_CHAT {
			priceData = append(priceData, dtos.PriceData{PriceType: constants.PRICE_TYPE_CODE_CHAT, PayPrice: int(priceConfig.PayPrice)})
		}
	}

	// 构建区域信息
	res := dtos.AnchorGetAnchorInfoResult{
		UserId:        strconv.FormatInt(anchorInfo.AnchorId, 10),
		SubRegionId:   anchorInfo.SubRegionId,
		Status:        anchorInfo.Status,
		DisableStatus: anchorInfo.DisableStatus,
		Price:         priceData,
		LiveModel:     anchorInfo.LiveModel,
	}

	// 返回成功结果
	c.Result(constants.SUCCESS, res)
}

// 获取主播对聊资料
func (c *AnchorController) GetVideoCallMaterials() {

	req := dtos.AnchorGetVideoCallMaterialsParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误 ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	// 获取主播信息
	anchorInfo, err := models.GetAnchor_infoByAnchorId(req.UserId)
	if err != nil {
		c.Error("查询anchor_info失败:", err.Error(), req.UserId)
		c.Result(constants.ERR_USER_NOT_EXIST, nil)
		return
	}

	// 获取主播资料
	apply, err := models.GetVideo_call_materials_auditByAnchorId(req.UserId)

	if err != nil && !errors.Is(err, orm.ErrNoRows) {
		c.Error("查询video_call_materials_audit失败:", err.Error(), req.UserId)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	if errors.Is(err, orm.ErrNoRows) || apply.Id == 0 {
		c.Error("查询video_call_materials_audit失败:未找到数据", req.UserId)
		c.Result(constants.ERR_MATERIAL_NOT_FOUND, nil)
		return
	}

	res := dtos.AnchorGetVideoCallMaterialsResult{
		UserId:               strconv.FormatInt(anchorInfo.AnchorId, 10),
		MaterialsAuditStatus: apply.Status,
		Reason:               apply.Reason,
		MaterialList:         []dtos.MaterialListItem{},
	}

	// 获取主播资料详情
	materialList, err := models.GetVideo_call_materials_audit_detailByAnchor(anchorInfo.AnchorId, apply.Id)

	if err != nil && !errors.Is(err, orm.ErrNoRows) {
		c.Error("查询video_call_materials_audit_detail失败:", err.Error(), req.UserId)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	if errors.Is(err, orm.ErrNoRows) || len(materialList) == 0 {
		c.Error("查询video_call_materials_audit_detail失败:未找到数据", req.UserId)
		c.Result(constants.ERR_MATERIAL_NOT_FOUND, nil)
		return
	}

	for _, v := range materialList {
		contentStr := v.Content
		var content models.MaterialContent
		err = json.Unmarshal([]byte(contentStr), &content)
		if err != nil {
			c.Error("json解析失败:", err.Error(), contentStr)
			c.Result(constants.ERR_SYS, nil)
			return
		}
		fileHost := ""
		msg := content.Msg
		if v.ContentType != constants.MATERIAL_CONTENT_TYPE_TEXT {
			fileHost = configs.FileHost
			msg = v.FilePath
		}
		res.MaterialList = append(res.MaterialList, dtos.MaterialListItem{
			Id:            int(v.Id),
			FileHost:      fileHost,
			MaterialsType: v.MaterialsType,
			Msg:           msg,
			MsgType:       v.ContentType,
			Duration:      content.Duration,
		})
	}

	c.Result(constants.SUCCESS, res)
}

// TODO:添加主播对聊资料
func (c *AnchorController) AddVideoCallMaterialsAudit() {

	req := dtos.AnchorAddVideoCallMaterialsAuditParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误 ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	userProfileData, err := models.GetUser_profileByUserId(req.UserId)

	if err != nil {
		c.Error("GetUser_profileById失败:", err.Error())
		c.Result(constants.ERR_SYS, nil)
		return
	}

	if userProfileData.Gender != constants.SEX_FEMALE {
		c.Result(constants.ERR_USER_NOT_ALLOW, nil)
		return
	}

	hasAnchor := false
	delUserFlag := false
	timestamp := time.Now().Unix()

	anchorInfo, err := models.GetAnchor_infoByAnchorId(req.UserId)
	if err == nil && anchorInfo.AnchorId != 0 {
		hasAnchor = true
	}

	var defaultConfig = new(models.Video_call_price_config)
	var defaultChatConfig = new(models.Video_call_price_config)
	if hasAnchor {
		var materialAudit models.Video_call_materials_audit
		materialAudit, err = models.GetVideo_call_materials_auditByAnchorId(req.UserId)
		if err != nil && !errors.Is(err, orm.ErrNoRows) {
			c.Error("GetVideo_call_materials_auditByAnchorId失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_SYS, nil)
			return
		}
		if err == nil && materialAudit.Status == constants.MATERIALS_AUDITING {
			c.Error("资料审核中不能再次提交", materialAudit.Status, req.UserId)
			c.Result(constants.ERR_MATERIAL_AUDITING, nil)
			return
		}
	} else {

		usersData, err := models.GetUsersByUserId(req.UserId)

		if err != nil && !errors.Is(err, orm.ErrNoRows) {
			c.Error("GetUser_profileById失败:", err.Error())
			c.Result(constants.ERR_SYS, nil)
			return
		}

		if usersData.UserId > 0 {
			delUserFlag = true
		}

		anchorInfo = &models.Anchor_info{
			AnchorId:      req.UserId,
			Status:        constants.ANCHOR_ONLINEIDLE,
			DisableStatus: constants.DISABLE_BY_MATERIALS,
			LiveModel:     constants.LIVE_MODEL_LEAVE,
			ActiveTime:    timestamp,
		}

		defaultConfig, err = models.GetVideo_call_price_AnchorDefault()

		if err != nil {
			c.Error("GetVideo_call_price_AnchorDefault失败:", err.Error())
			c.Result(constants.ERR_SYS, nil)
			return
		}

		defaultChatConfig, err = models.GetVideo_call_price_AnchorDefaultChat()

		if err != nil {
			c.Error("GetVideo_call_price_AnchorDefaultChat失败:", err.Error())
			c.Result(constants.ERR_SYS, nil)
			return
		}

	}

	subRegionId := 0
	regionInfo, err := models.GetSub_region_configurationByCode(req.CountryCode)
	if err == nil && regionInfo.RegionId > 0 {
		subRegionId = regionInfo.RegionId
	}

	anchorInfo.SubRegionId = subRegionId

	if hasAnchor {
		err = models.UpdateAnchor_infoByAnchorId(anchorInfo)
		if err != nil {
			c.Error("UpdateAnchor_infoByAnchorId失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}
	} else {
		_, err = models.AddAnchor_info(anchorInfo)
		if err != nil {
			c.Error("AddAnchor_info失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}
	}

	if userProfileData.Identity == constants.IDENTITY_NORMAL_USER {
		userProfileData.Identity = constants.IDENTITY_APPLY_ANCHOR
		userProfileData.UpdateTime = timestamp
		err = models.UpdateUser_profileById(userProfileData)
		if err != nil {
			c.Error("UpdateUserProfileIdentity失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}
	}

	if delUserFlag {
		err = models.DeleteUsers(req.UserId)
		if err != nil {
			c.Error("DeleteUsersByUserId失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}
	}

	materialAuditAdd := models.Video_call_materials_audit{
		AnchorId:   req.UserId,
		Status:     constants.MATERIALS_AUDITING,
		ApplyTime:  timestamp,
		CreateTime: timestamp,
		UpdateTime: timestamp,
	}

	var auditId int64
	auditId, err = models.AddVideo_call_materials_audit(&materialAuditAdd)

	if err != nil || auditId == 0 {
		c.Error("AddVideo_call_materials_audit失败:err=%s,userid=%d,auditId=", err.Error(), req.UserId, auditId)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	_, _ = models.DeleteHistoryVideo_call_materials_audit(req.UserId, auditId)

	materialAdds := []models.Video_call_materials_audit_detail{}
	for k, v := range req.MaterialList {

		filePathHash := ""
		msg := ""
		if v.MsgType != constants.MATERIAL_CONTENT_TYPE_TEXT {
			filePathHash = utils.Md5(v.Msg)
			msg = configs.FileHost + v.Msg
		} else {
			msg = v.Msg
		}

		var contentByte []byte
		contentByte, err = json.Marshal(models.MaterialContent{
			Msg:      msg,
			Duration: v.Duration,
		})
		if err != nil {
			c.Error("资料content json序列化失败:key=%d", k, err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}

		materialAdds = append(materialAdds, models.Video_call_materials_audit_detail{
			AnchorId:      req.UserId,
			AuditId:       auditId,
			MaterialsType: v.MaterialsType,
			Content:       string(contentByte),
			FilePath:      v.Msg,
			ContentType:   v.MsgType,
			FilePathHash:  filePathHash,
			CreateTime:    timestamp,
			UpdateTime:    timestamp,
		})
	}

	var num int64
	num, err = models.AddVideo_call_materials_audit_detailBatch(&materialAdds)

	if err != nil || num == 0 {
		c.Error("AddVideo_call_materials_audit_detailBatch失败:", err.Error(), req.UserId)
		c.Result(constants.ERR_MATERIAL_UPDATE, nil)
		return
	}

	if !hasAnchor {
		videoCallPrice := models.Video_call_price{
			AnchorId:  req.UserId,
			PriceType: constants.PRICE_TYPE_ID_VIDEO_CALL,
			Price:     defaultConfig.Id,
		}

		_, err = models.AddVideo_call_price(&videoCallPrice)
		if err != nil {
			c.Error("AddVideo_call_price.video_call失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}

		videoCallPriceChat := models.Video_call_price{
			AnchorId:  req.UserId,
			PriceType: constants.PRICE_TYPE_ID_CHAT,
			Price:     defaultChatConfig.Id,
		}

		_, err = models.AddVideo_call_price(&videoCallPriceChat)
		if err != nil {
			c.Error("AddVideo_call_price.chat失败:", err.Error(), req.UserId)
			c.Result(constants.ERR_MATERIAL_UPDATE, nil)
			return
		}
	}

	go services.SyncUserData(strconv.FormatInt(req.UserId, 10), constants.DATA_UPDATED_USER_IDENTITY_UPDATED, nil)

	res := dtos.AnchorAddVideoCallMaterialsAuditResult{
		IsFirstSubmit: !hasAnchor,
	}

	c.Result(constants.SUCCESS, res)
}

func (c *AnchorController) GetVideoCallPriceConfig() {

	req := dtos.AnchorGetSysPriceListParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误 ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	// 获取主播信息
	_, err = models.GetAnchor_infoByAnchorId(req.UserId)
	if err != nil {
		c.Result(constants.ERR_USER_NOT_EXIST, nil)
		return
	}

	// 获取主播价格信息
	anchorPrice, err := models.GetVideo_call_priceByAnchorId(req.UserId, constants.PRICE_TYPE_ID_VIDEO_CALL)
	if err != nil {
		c.Error("查询video_call_price失败:", err.Error(), req.UserId)
		c.Result(constants.ERR_USER_DATA_EXCPTION, nil)
		return
	}

	var anchorPriceConfig models.Video_call_price_config
	if anchorPrice.Price != 0 {
		var priceConfig *models.Video_call_price_config
		priceConfig, err = models.GetVideo_call_price_configById(anchorPrice.Price)
		if err != nil {
			c.Error("查询video_call_price_config失败:", err.Error(), anchorPrice.Price)
			c.Result(constants.ERR_USER_DATA_EXCPTION, nil)
			return
		}
		anchorPriceConfig = *priceConfig
	}

	// 获取系统价格列表
	priceList, err := models.GetVideo_call_price_configList(constants.PRICE_TYPE_ID_VIDEO_CALL)
	if err != nil {
		c.Error("查询video_call_price_config失败:", err.Error())
		c.Result(constants.ERR_SYS, nil)
		return
	}

	var res dtos.AnchorGetSysPriceListResult

	// 添加系统价格列表
	isAppend := false
	for _, v := range priceList {
		// 添加主播当前价格
		if anchorPriceConfig.Id != 0 && anchorPriceConfig.AnchorPrice < v.AnchorPrice {
			res.ConfigList = append(res.ConfigList, dtos.SysPriceItem{Id: anchorPriceConfig.Id, AnchorPrice: int(anchorPriceConfig.AnchorPrice), IsInUse: true})
			isAppend = true
		}

		if v.Id != anchorPriceConfig.Id {
			res.ConfigList = append(res.ConfigList, dtos.SysPriceItem{Id: v.Id, AnchorPrice: int(v.AnchorPrice), IsInUse: false})
		}
	}

	if !isAppend && anchorPriceConfig.Id != 0 {
		res.ConfigList = append(res.ConfigList, dtos.SysPriceItem{Id: anchorPriceConfig.Id, AnchorPrice: int(anchorPriceConfig.AnchorPrice), IsInUse: true})
	}

	c.Result(constants.SUCCESS, res)
}

func (c *AnchorController) UpdateVideoCallPrice() {

	req := dtos.AnchorUpdateVideoCallPriceParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("GetSysPriceList参数错误 ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	// 获取主播信息
	anchorInfo, err := models.GetAnchor_infoByAnchorId(req.UserId)

	if err != nil {
		c.Result(constants.ERR_USER_NOT_EXIST, nil)
		return
	}

	allowUpdate := anchorInfo.Status == constants.ANCHOR_ONLINEIDLE || anchorInfo.Status == constants.ANCHOR_OFFLINE

	// 检查主播状态
	if !allowUpdate {
		c.Result(constants.ERR_ANCHOR_IS_BUSY, nil)
		return
	}

	curPrice, err := models.GetVideo_call_priceByAnchorId(req.UserId, constants.PRICE_TYPE_ID_VIDEO_CALL)

	if err != nil {
		c.Result(constants.ERR_USER_DATA_EXCPTION, nil)
		return
	}

	if curPrice.Price == req.PriceConfigId {
		c.Result(constants.SUCCESS, nil)
		return
	}

	// 验证价格配置
	priceConfig, err := models.GetVideo_call_price_ByIdAndType(req.PriceConfigId)
	if err != nil {
		c.Result(constants.ERR_PRICE_ID_NOT_EXIST, nil)
		return
	}

	// 更新价格信息
	videoCallPrice := models.Video_call_price{
		AnchorId:  req.UserId,
		PriceType: constants.PRICE_TYPE_ID_VIDEO_CALL,
		Price:     priceConfig.Id,
	}

	err = models.UpdateVideo_call_priceByIdAndType(&videoCallPrice)
	if err != nil {
		c.Result(constants.ERR_PRICE_UPDATE, nil)
		return
	}

	go services.SyncUserData(strconv.FormatInt(req.UserId, 10), constants.DATA_UPDATED_ANCHOR_PAY_PRICE_UPDATED, nil)

	c.Result(constants.SUCCESS, nil)
}

// CompleteUserInfo 完善用户信息（头像和昵称）
func (c *AnchorController) CompleteUserInfo() {

	req := dtos.CompleteUserInfoParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("CompleteUserInfo参数错误 ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	userId := req.UserId

	identity, err := models.GetUserIdentityByUserId(userId)
	if err != nil {
		c.Error("获取用户身份失败:GetUserIdentityByUserId(%v): %v", userId, err)
		c.Result(constants.ERR_GET_USER_IDENTITY_FAIL, nil)
		return
	}

	var updateCacheFields map[string]interface{}
	updateCacheFields = make(map[string]interface{})

	// 根据性别喷段跟新主播还是用户
	if identity == constants.IDENTITY_NORMAL_USER {
		// 判断用户存在
		user, err := models.GetUsersByUserId(req.UserId)
		if err == nil && user != nil {
			// 只对已有的用户更新值
			userNew := models.Users{
				UserId: req.UserId,
			}
			updateFields := []string{}
			// 如果昵称不为空，更新昵称
			if req.Nick != "" {
				userNew.Nick = req.Nick
				updateFields = append(updateFields, "nick")
				updateCacheFields["nick"] = req.Nick
			}
			// 如果头像不为空，更新头像
			if req.HeadImg != "" && req.HeadImg != "null" {
				userNew.HeadImg = req.HeadImg
				updateFields = append(updateFields, "head_img")
				updateCacheFields["head_img"] = req.HeadImg
			}

			if req.Age != 0 {
				userNew.Age = req.Age
				updateFields = append(updateFields, "age")
				updateCacheFields["age"] = req.Age
			}

			if req.Gender != 0 {
				userNew.Age = req.Gender
				updateFields = append(updateFields, "gender")
				updateCacheFields["gender"] = req.Gender
			}

			if len(updateFields) > 0 {
				err = models.UpdateUsersByUserIdAndFields(&userNew, updateFields)
				if err != nil {
					c.Error("更新用户信息失败:UpdateUsersByUserIdAndFields(%+v, %v): %v", &userNew, updateFields, err)
					c.Result(constants.ERR_WS_UPDATE_USER_FAIL, nil)
					return
				}
			}
		}
	} else {
		// 判断主播存在
		anchorInfo, err := models.GetAnchor_infoByAnchorId(req.UserId)
		if err == nil && anchorInfo != nil {
			// 只对已有的用户更新值
			anchorNew := models.Anchor_info{
				AnchorId: req.UserId,
			}
			updateFields := []string{}
			// 如果昵称不为空，更新昵称
			if req.Nick != "" {
				anchorNew.Nick = req.Nick
				updateFields = append(updateFields, "nick")
				updateCacheFields["nick"] = req.Nick
			}
			// 如果头像不为空，更新头像
			if req.HeadImg != "" && req.HeadImg != "null" {
				anchorNew.HeadImg = req.HeadImg
				updateFields = append(updateFields, "head_img")
				updateCacheFields["head_img"] = req.HeadImg
			}

			// 如果年龄不为空，更新头像
			if req.Age != 0 {
				anchorNew.Age = req.Age
				updateFields = append(updateFields, "age")
				updateCacheFields["age"] = req.Age
			}

			if req.Gender != 0 {
				anchorNew.Age = req.Gender
				updateFields = append(updateFields, "gender")
				updateCacheFields["gender"] = req.Gender
			}
			if len(updateFields) > 0 {
				err = models.UpdateAnchor_infoByAnchorIdAndFields(&anchorNew, updateFields)
				if err != nil {
					c.Error("更新用户信息失败:UpdateAnchor_infoByAnchorIdAndFields(%+v, %v): %v", &anchorNew, updateFields, err)
					c.Result(constants.ERR_WS_UPDATE_USER_FAIL, nil)
					return
				}
			}
		}
	}

	// 如果性别不为空，更新 user_profile
	if req.Gender != 0 {
		userProfileNew := models.User_profile{
			UserId: req.UserId,
			Gender: req.Gender,
		}
		err = models.UpdateUser_profileByUserIdAndFields(&userProfileNew, []string{"gender"})
		if err != nil {
			c.Error("更新用户信息失败:UpdateUser_profileByUserIdAndFields(%+v, %v): %v", &userProfileNew, []string{"gender"}, err)
			c.Result(constants.ERR_WS_UPDATE_USER_FAIL, nil)
		}
	}

	redisserver := new(utils.RedisService)
	if err = services.UpdateUserCacheFields(redisserver, req.UserIdStr, updateCacheFields); err != nil {
		c.Error("同步更新用户缓存失败:UpdateUserCacheFields(%v): %v", req.UserIdStr, err)
		c.Result(constants.ERR_WS_UPDATE_USER_CACHE_FAIL, nil)
	}

	// mq 同步用户信息
	go services.SyncUserData(req.UserIdStr, constants.DATA_UPDATED_USER_INFO_UPDATED, nil)

	c.Result(constants.SUCCESS, nil)
}

// LiveStatusNotify 更新直播状态
func (c *AnchorController) LiveStatusNotify() {

	req := dtos.UpdateLiveStatusParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("UpdateLiveStatus参数错误 ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	var masterResultPtr *[]dtos.MaterApiVideocallSearchData

	anchorInfo, err := models.GetAnchor_live_statusByAnchorId(req.UserId)

	if err != nil && !errors.Is(err, orm.ErrNoRows) {
		c.Error("查询anchor_live_status失败:", err.Error())
		c.Result(constants.ERR_SYS, nil)
		return
	}

	if anchorInfo == nil {
		anchorInfo = &models.Anchor_live_status{}
	}

	// 如果是开播，请求远程接口 http://goapi.sjlive.cn/videocall/search 获取主播详细信息
	if req.LiveStatus == constants.ANCHOR_LIVE_STATUS_LIVE || anchorInfo.Nick == "" {
		// 获取主播信息
		masterResultPtr, err = services.VideocallSearch(req.UserIdStr)
		if err != nil {
			c.Error("请求搜索主播接口失败:VideocallSearch(%v): err=%v", req.UserIdStr, err)
			c.Result(constants.ERR_COCO_SEARCH_FAIL, nil)
			return
		}

		masterResult := *masterResultPtr

		if len(masterResult) != 1 {
			c.Error("请求主播信息失败:VideocallSearch(%v): masterResult.Data is empty", req.UserIdStr)
			c.Result(constants.ERR_COCO_SEARCH_FAIL, nil)
			return
		}

		var subRegionInfo *models.Sub_region_configuration
		if req.SubRegionId > 0 {
			subRegionInfo, err = models.GetSub_region_configurationByRegionId(req.SubRegionId)

			if err != nil && !errors.Is(err, orm.ErrNoRows) {
				c.Error("查询sub_region_configuration失败:", err.Error(), "req.SubRegionId=", req.SubRegionId)
				c.Result(constants.ERR_SYS, nil)
				return
			}

			anchorInfo.SubRegionId = req.SubRegionId
			anchorInfo.FlagImage = subRegionInfo.FlagImage
		}

		birthday, _ := strconv.Atoi(masterResult[0].Birthday)
		year := utils.TimestampToDatetime(int64(birthday), "2006")
		yearInt, _ := strconv.Atoi(year)
		yearNowInt, _ := strconv.Atoi(time.Now().Format("2006"))

		anchorInfo.LiveType = req.LiveType
		anchorInfo.Nick = masterResult[0].NickName
		anchorInfo.HeadImg = masterResult[0].AvatarUrl
		anchorInfo.Gender, _ = strconv.Atoi(masterResult[0].Gender)
		anchorInfo.Age = yearNowInt - yearInt

	}

	anchorInfo.UpdateTime = time.Now().Unix()
	anchorInfo.LiveStatus = req.LiveStatus

	if anchorInfo.AnchorId == 0 {
		anchorInfo.AnchorId = req.UserId
		err = models.AddAnchor_live_status(anchorInfo)
	} else {
		err = models.UpdateAnchor_live_status(anchorInfo)
	}

	if err != nil {
		c.Error("更新用户信息失败:UpdateAnchor_infoByAnchorIdAndFields(%+v): %v", &anchorInfo, err)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	c.Result(constants.SUCCESS, nil)
}
